package com.xros.demo.gamedataserver.codec;

import com.alibaba.fastjson.JSONObject;
import com.xros.demo.gamedataserver.domian.message.CustomerMessage;
import com.xros.demo.gamedataserver.domian.message.MessageWrapper;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import io.netty.handler.codec.MessageToMessageCodec;
import io.netty.handler.codec.json.JsonObjectDecoder;
import lombok.extern.log4j.Log4j2;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Random;

/**
 * @Author: mzp
 * @Description: 自定义消息处理器
 * @Date: 2024/3/26 17:12
 * @Version: 1.0
 */
@Log4j2

public class CustomerMessageCodec extends MessageToMessageCodec<ByteBuf,CustomerMessage> {


    private byte version = 0;

    private byte algorithm = 0;

    /**
     * 编码操作
     * @param ctx
     * @param msg
     * @param toSendMsg
     * @throws Exception
     */
    @Override
    protected void encode(ChannelHandlerContext ctx, CustomerMessage msg, List<Object> toSendMsg) throws Exception {

        ByteBuf out = ctx.alloc().buffer();
        log.info("开始编码操作...");
        //魔数
        out.writeInt(getMagicNumber());

        //版本号
        out.writeByte(version);

        //序列化算法,0-json
        out.writeByte(algorithm);

        //消息类型
        out.writeByte(msg.getMsgType());

        //序列号
        out.writeInt(getSequence());


        byte[] content = getInstanceBytes(msg);


        if (content.length < 1) {
            throw new Exception("发送的消息数据异常");
        }
        //消息长度
        out.writeInt(content.length);

        //caffe
        out.writeByte(7);

        //内容
        out.writeBytes(content);


        toSendMsg.add(out);

    }

    /**
     * 解码操作
     *
     * @param ctx
     * @param in
     * @param out
     * @throws Exception
     */
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

        log.info("开始解码操作...");
        //魔数字
        int magicNum = in.readInt();

        //版本号
        byte version = in.readByte();

        //序列化算法,0-json
        byte algorithm = in.readByte();


        byte msgType = in.readByte();

        //序列号
        int sequence = in.readInt();

        //消息长度
        int len = in.readInt();

        //caffe
        byte caff = in.readByte();


        byte[] content = new byte[len];
        log.info("in === {}",in);

        //读取内容到上面的缓冲区
//        int reaming = in.readableBytes();
        in.readBytes(content);




        //region 将数据进行包装


        MessageWrapper msgWrapper = new MessageWrapper();

        msgWrapper.setMagicNumber(magicNum);
        msgWrapper.setVersion(version);
        msgWrapper.setAlgorithm(algorithm);
        msgWrapper.setMsgType(msgType);
        msgWrapper.setSequence(sequence);
        msgWrapper.setLength(len);
        boolean setResult = msgWrapper.setContentByMsgType(content);


        //endregion

        if(!setResult){
            throw new Exception("设置消息的包装数据出现错误");
        }

        log.info("解码过后的 msgWrapper === {}",JSONObject.toJSONString(msgWrapper));

        out.add(msgWrapper);


    }


    private <T> byte[] getInstanceBytes(T instance) {
        byte[] result = new byte[]{};
        if (algorithm == 0) {
            final String jsonString = JSONObject.toJSONString(instance);
            result = jsonString.getBytes(StandardCharsets.UTF_8);
        } else {

        }
        return result;
    }


    //region 需要提取的工具方法

    private Random random = new Random();

    public int getMagicNumber() {
        return random.nextInt(10000);
    }

    public int getSequence() {
        return random.nextInt(100000);
    }

    //endregion

}
